import os
import sys

# 确保能找到所需的DLL文件
if getattr(sys, 'frozen', False):
    # 如果是打包后的exe运行
    application_path = os.path.dirname(sys.executable)
    os.environ['PATH'] = application_path + os.pathsep + os.environ['PATH']
    
    # 添加可能的DLL目录
    possible_dll_dirs = [
        application_path,
        os.path.join(application_path, 'cv2'),
        os.path.join(application_path, 'numpy')
    ]
    
    for dll_dir in possible_dll_dirs:
        if os.path.exists(dll_dir):
            if hasattr(os, 'add_dll_directory'):
                os.add_dll_directory(dll_dir)

import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QFileDialog, 
                           QVBoxLayout, QHBoxLayout, QWidget, QLabel, QProgressBar)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from manga_panel_extractor import MangaPanelExtractor

class ExtractorThread(QThread):
    progress = pyqtSignal(int)
    finished = pyqtSignal()
    error = pyqtSignal(str)

    def __init__(self, input_dir, output_dir):
        super().__init__()
        self.input_dir = input_dir
        self.output_dir = output_dir
        self.extractor = MangaPanelExtractor()

    def run(self):
        try:
            # 获取所有图片文件
            image_files = [f for f in os.listdir(self.input_dir) 
                         if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]
            total_files = len(image_files)

            for i, image_file in enumerate(image_files):
                input_path = os.path.join(self.input_dir, image_file)
                # 为每个图片创建一个子文件夹
                output_subdir = os.path.join(self.output_dir, os.path.splitext(image_file)[0])
                
                try:
                    self.extractor.extract_panels(input_path, output_subdir)
                except Exception as e:
                    print(f"Error processing {image_file}: {str(e)}")
                
                # 更新进度
                progress = int((i + 1) / total_files * 100)
                self.progress.emit(progress)

            self.finished.emit()
        except Exception as e:
            self.error.emit(str(e))

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("漫画分镜提取工具")
        self.setMinimumSize(600, 200)
        self.setup_ui()

    def setup_ui(self):
        # 创建主窗口部件和布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        layout = QVBoxLayout(main_widget)

        # 输入文件夹选择
        input_layout = QHBoxLayout()
        self.input_label = QLabel("输入文件夹：")
        self.input_path = QLabel("未选择")
        self.input_button = QPushButton("选择文件夹")
        self.input_button.clicked.connect(self.select_input_folder)
        input_layout.addWidget(self.input_label)
        input_layout.addWidget(self.input_path)
        input_layout.addWidget(self.input_button)

        # 输出文件夹选择
        output_layout = QHBoxLayout()
        self.output_label = QLabel("输出文件夹：")
        self.output_path = QLabel("未选择")
        self.output_button = QPushButton("选择文件夹")
        self.output_button.clicked.connect(self.select_output_folder)
        output_layout.addWidget(self.output_label)
        output_layout.addWidget(self.output_path)
        output_layout.addWidget(self.output_button)

        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setAlignment(Qt.AlignCenter)

        # 开始按钮
        self.start_button = QPushButton("开始处理")
        self.start_button.clicked.connect(self.start_processing)
        self.start_button.setEnabled(False)

        # 添加所有部件到主布局
        layout.addLayout(input_layout)
        layout.addLayout(output_layout)
        layout.addWidget(self.progress_bar)
        layout.addWidget(self.start_button)

        # 状态标签
        self.status_label = QLabel("")
        layout.addWidget(self.status_label)

    def select_input_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "选择输入文件夹")
        if folder:
            self.input_path.setText(folder)
            self.check_start_button()

    def select_output_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "选择输出文件夹")
        if folder:
            self.output_path.setText(folder)
            self.check_start_button()

    def check_start_button(self):
        input_selected = self.input_path.text() != "未选择"
        output_selected = self.output_path.text() != "未选择"
        self.start_button.setEnabled(input_selected and output_selected)

    def start_processing(self):
        input_dir = self.input_path.text()
        output_dir = self.output_path.text()

        # 禁用按钮
        self.start_button.setEnabled(False)
        self.input_button.setEnabled(False)
        self.output_button.setEnabled(False)

        # 创建并启动处理线程
        self.thread = ExtractorThread(input_dir, output_dir)
        self.thread.progress.connect(self.update_progress)
        self.thread.finished.connect(self.processing_finished)
        self.thread.error.connect(self.processing_error)
        self.thread.start()

        self.status_label.setText("正在处理...")

    def update_progress(self, value):
        self.progress_bar.setValue(value)

    def processing_finished(self):
        self.status_label.setText("处理完成！")
        self.progress_bar.setValue(100)
        
        # 重新启用按钮
        self.start_button.setEnabled(True)
        self.input_button.setEnabled(True)
        self.output_button.setEnabled(True)

    def processing_error(self, error_msg):
        self.status_label.setText(f"发生错误: {error_msg}")
        
        # 重新启用按钮
        self.start_button.setEnabled(True)
        self.input_button.setEnabled(True)
        self.output_button.setEnabled(True)

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main() 